package com.lzc.tlmall.tlmallauthservice.controller;

import com.alibaba.fastjson.TypeReference;
import com.lzc.common.utils.R;
import com.lzc.common.vo.MemberEntityVo;
import com.lzc.common.constant.OauthConstant;
import com.lzc.tlmall.tlmallauthservice.feign.UserFeignService;
import com.lzc.tlmall.tlmallauthservice.vo.LoginVo;
import com.lzc.tlmall.tlmallauthservice.vo.RegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lzc
 * @create 2020-10-11 20:11
 */
@Controller
public class UserController {


    @Autowired
    private UserFeignService userFeignService;

    /**
     * 注册方法
     * @param registVo
     * @param bindingResult
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid RegistVo registVo, BindingResult bindingResult, RedirectAttributes redirectAttributes){
        if(bindingResult.hasErrors()){
            Map<String, String> errors = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://www.auth.tlmail.com/reg.html";
        }else {
            //TODO   调用会员服务进行注册
            R regist = userFeignService.regist(registVo);
            if(regist.getCode()==0){
                return "redirect:http://www.auth.tlmail.com/login.html";
            }else{
                Map<String,String> errors=new HashMap<>();
                errors.put("msg",regist.getData("msg",new TypeReference<String>(){}));
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://www.auth.tlmail.com/reg.html";
            }

        }


    }

    /**
     * 登录方法
     * @return
     */
    @PostMapping("/login")
    public String login(LoginVo loginVo, RedirectAttributes redirectAttributes, HttpSession session){
        R login = userFeignService.login(loginVo);
        if(login.getCode()==0){
            MemberEntityVo loginData = login.getData("data", new TypeReference<MemberEntityVo>() {
            });
            session.setAttribute(OauthConstant.OAUTH_LOGINUSER,loginData);
            return "redirect:http://www.tlmail.com";
        }else {
            Map<String,String> errors=new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://www.auth.tlmail.com/login.html";
        }


    }
}
